<?php

defined('BASEPATH') OR exit('No direct script access allowed');

class Backend extends CI_Controller {

    public $render_data;

    function __construct() {
        parent::__construct();
        if ($this->uri->segment(1) == 'backend' || !$this->session->userdata('user_id')) {
            show_404();
        }

        // Check Login //
        $this->render_data['user_id'] = null;
        $this->render_data['is_admin'] = 0;
        $this->render_data['fb_id'] = 0;
        $this->render_data['fullname'] = 0;

        if ($this->session->userdata('user_id')) {

            $this->render_data['user_id'] = $this->session->userdata('user_id');
            $this->render_data['fb_id'] = $this->session->userdata('fb_id');
            $this->render_data['is_admin'] = $this->session->userdata('is_admin');

            if ($this->render_data['is_admin'] != 1) {
                redirect('/');
            }

            $this->render_data['fullname'] = $this->session->userdata('fullname');
        }
    }

    function index() {
        redirect('admin/campaign/list');
    }

    // <editor-fold desc="Campaign">



    function campaign_list() {
        $this->load->library(array('template', 'carabiner'));

        $this->load->model('campaign_model', 'campaign');
        $this->render_data['campaign_list'] = $this->campaign->list_campaign_get_sponsor_logo();


        $this->template->write_view('main_nav', 'partials/main_nav', $this->render_data);
        $this->render_data['admin_content'] = $this->load->view('admin/campaign_list', $this->render_data, TRUE);
        $this->template->write_view('content', 'admin/admin_wrapper', $this->render_data);


        $this->template->write('title', 'รายการการแข่งขัน < จัดการรายการแข่งขัน | ' . WEB_TITLE);
        $this->template->render();
    }

    function export_candidate_csv($campaign_id) {
        $query = $this->db->select('title,sum_positive_score,sum_negative_score,sum_wilson_score,sum_view,campaign_joins.created_at,users.fb_id,users.firstname,users.lastname,users.birthday,users.email,users.gender,users.telephone,users.address')
                ->join('users', 'user_id=users.id')
                ->where('campaign_id', $campaign_id)
                ->get('campaign_joins');
        $csv_data = '"ชื่อผลงาน","คะแนนโหวตชอบ","คะแนนโหวตไม่ชอบ","คะแนนโหวตรวม","จำนวนผู้ชม","สร้างเมื่อ","FB ID","ชื่อจริง","นามสกุล","อายุ","เพศ","อีเมล์","เบอร์ติดต่อ","ที่อยู่"' . PHP_EOL;

        if ($query->num_rows() > 0) {

            function getAge($birth) {
                $t = time();
                $age = ($birth < 0) ? ( $t + ($birth * -1) ) : $t - $birth;
                return floor($age / 31536000);
            }

            $result = $query->result_array();
            foreach ($result as $row) {
                $csv_data .= '"' . $row['title'] . '",';
                $csv_data .= '"' . $row['sum_positive_score'] . '",';
                $csv_data .= '"' . $row['sum_negative_score'] . '",';
                $csv_data .= '"' . $row['sum_wilson_score'] . '",';
                $csv_data .= '"' . $row['sum_view'] . '",';
                $csv_data .= '"' . date('d/m/Y H:i:s', $row['created_at']) . '",';
                $csv_data .= '"http://fb.com/' . $row['fb_id'] . '",';
                $csv_data .= '"' . $row['firstname'] . '",';
                $csv_data .= '"' . $row['lastname'] . '",';
                $csv_data .= '"' . getAge(strtotime($row['birthday'])) . '",';
                $csv_data .= '"' . ($row['gender'] == 'male' ? 'ชาย' : 'หญิง') . '",';
                $csv_data .= '"' . $row['email'] . '",';
                $csv_data .= '"' . $row['telephone'] . '",';
                $csv_data .= '"' . $row['address'] . '"' . PHP_EOL;
            }
        }

        $name = 'Candidates_' . date('d-m-Y His') . '.csv';
        header('Content-Type: application/csv; charset=UTF-8');
        header('Content-Disposition: attachement; filename="' . $name . '"');
        header('Pragma: public');
        echo "\xEF\xBB\xBF";
        echo $csv_data;
    }

    function export_member_csv($campaign_id) {
        $query = $this->db->select('SUM(positive_vote) as sum_positive_vote,SUM(negative_vote) as sum_negative_vote,SUM(view) as sum_view,users.fb_id,users.firstname,users.lastname,users.birthday,users.email,users.gender,users.telephone,users.address')
                ->join('users', 'user_id=users.id')
                ->where('campaign_id', $campaign_id)
                ->group_by('user_id')
                ->get('campaign_activities');
        $csv_data = '"รวมโหวตชอบ","รวมโหวตไม่ชอบ","รวมวิว","FB ID","ชื่อจริง","นามสกุล","อายุ","เพศ","อีเมล์","เบอร์ติดต่อ"' . PHP_EOL;

        if ($query->num_rows() > 0) {

            function getAge($birth) {
                $t = time();
                $age = ($birth < 0) ? ( $t + ($birth * -1) ) : $t - $birth;
                return floor($age / 31536000);
            }

            $result = $query->result_array();
            foreach ($result as $row) {
                $csv_data .= '"' . $row['sum_positive_vote'] . '",';
                $csv_data .= '"' . $row['sum_negative_vote'] . '",';
                $csv_data .= '"' . $row['sum_view'] . '",';
                $csv_data .= '"http://fb.com/' . $row['fb_id'] . '",';
                $csv_data .= '"' . $row['firstname'] . '",';
                $csv_data .= '"' . $row['lastname'] . '",';
                $csv_data .= '"' . getAge(strtotime($row['birthday'])) . '",';
                $csv_data .= '"' . ($row['gender'] == 'male' ? 'ชาย' : 'หญิง') . '",';
                $csv_data .= '"' . $row['email'] . '",';
                $csv_data .= '"' . $row['telephone'] . '",';
                $csv_data .= '"' . $row['address'] . '"' . PHP_EOL;
            }
        }

        $name = 'Members_' . date('d-m-Y His') . '.csv';
        header('Content-Type: application/csv; charset=UTF-8');
        header('Content-Disposition: attachement; filename="' . $name . '"');
        header('Pragma: public');
        echo "\xEF\xBB\xBF";
        echo $csv_data;
    }

    function campaign_add() {
        $this->load->library(array('template', 'carabiner', 'form_validation'));

        if ($_POST) {
            $this->form_validation->set_rules('sponsor_id', 'Sponsor', 'required|is_natural');
            $this->form_validation->set_rules('title', 'Title', 'required|trim');
            $this->form_validation->set_rules('is_private', 'Is Private', 'required|is_natural');
            $this->form_validation->set_rules('description', 'Description', 'required');
            $this->form_validation->set_rules('positive_score_reward', 'Position Score Reward', 'required');
            $this->form_validation->set_rules('view_score_reward', 'View Score Reward', 'required');
            $this->form_validation->set_rules('wilson_score_reward', 'Wilson Score Reward', 'required');
            //$this->form_validation->set_rules('elo_score_reward', 'Battle Reward', 'required');

            $this->form_validation->set_rules('starting_at', 'starting_at', 'required');
            $this->form_validation->set_rules('stopped_at', 'stopped_at', 'required');

            $this->form_validation->set_rules('candidate_vdo', 'Candidate Vdo', 'required');
            $this->form_validation->set_rules('candidate_image', 'Candidate Image', 'required');
            $this->form_validation->set_rules('candidate_text', 'Candidate PDF', 'required');

            $this->form_validation->set_rules('highlight', 'Highlight', 'required');
            $this->form_validation->set_rules('highlight_interval', 'Highlight Interval', 'required');


            if ($this->form_validation->run() !== FALSE) {
                $this->load->model('campaign_model', 'campaign');
                $data_save = array(
                    'sponsor_id' => $this->input->post('sponsor_id'),
                    'title' => $this->input->post('title'),
                    'is_private' => $this->input->post('is_private'),
                    'description' => $this->input->post('description'),
                    'highlight' => $this->input->post('highlight'),
                    'highlight_interval' => $this->input->post('highlight_interval'),
                    'candidate_vdo' => $this->input->post('candidate_vdo'),
                    'candidate_image' => $this->input->post('candidate_image'),
                    'candidate_text' => $this->input->post('candidate_text'),
                    'starting_at' => strtotime($this->input->post('starting_at')),
                    'stopped_at' => strtotime($this->input->post('stopped_at')),
                    'positive_score_reward' => $this->input->post('positive_score_reward'),
                    'view_score_reward' => $this->input->post('view_score_reward'),
                    'wilson_score_reward' => $this->input->post('wilson_score_reward'),
                    //'elo_score_reward' => $this->_parse_reward($this->input->post('elo_score_reward')),
                );
                $this->campaign->add_campaign($data_save);
                redirect('admin/campaign/list');
            }
        }


        $this->render_data['js_indy'][] = 'ckeditor/ckeditor.js';
        $this->render_data['js_indy'][] = 'ckfinder/ckfinder.js';

        $this->render_data['js'][] = 'bootstrap-datetimepicker.min.js';
        $this->render_data['css'][] = 'bootstrap-datetimepicker.min.css';


        $this->template->write_view('main_nav', 'partials/main_nav', $this->render_data);

        $this->load->model('sponsor_model', 'sponsor');
        $this->render_data['sponsor_list'] = $this->sponsor->list_sponsor();
        $this->render_data['admin_content'] = $this->load->view('admin/campaign_add', $this->render_data, TRUE);
        $this->template->write_view('content', 'admin/admin_wrapper', $this->render_data);



        $this->template->write('title', 'เพิ่มการแข่งขัน < จัดการรายการแข่งขัน | ' . WEB_TITLE);
        $this->template->render();
    }

    function campaign_edit($campaign_id) {

        $campaign_id = floor($campaign_id);

        $this->load->library(array('template', 'carabiner', 'form_validation'));



        if ($_POST) {
            $this->form_validation->set_rules('sponsor_id', 'Sponsor', 'required|is_natural');
            $this->form_validation->set_rules('title', 'Title', 'required|trim');
            $this->form_validation->set_rules('is_private', 'Is Private', 'required|is_natural');
            $this->form_validation->set_rules('description', 'Description', 'required');
            $this->form_validation->set_rules('positive_score_reward', 'Position Score Reward', 'required');
            $this->form_validation->set_rules('view_score_reward', 'View Score Reward', 'required');
            $this->form_validation->set_rules('wilson_score_reward', 'Wilson Score Reward', 'required');
            //$this->form_validation->set_rules('elo_score_reward', 'Battle Reward', 'required');

            $this->form_validation->set_rules('starting_at', 'starting_at', 'required');
            $this->form_validation->set_rules('stopped_at', 'stopped_at', 'required');

            $this->form_validation->set_rules('candidate_vdo', 'Candidate Vdo', 'required');
            $this->form_validation->set_rules('candidate_image', 'Candidate Image', 'required');
            $this->form_validation->set_rules('candidate_text', 'Candidate PDF', 'required');

            $this->form_validation->set_rules('highlight', 'Highlight', 'required');
            $this->form_validation->set_rules('highlight_interval', 'Highlight Interval', 'required');


            if ($this->form_validation->run() !== FALSE) {
                $this->load->model('campaign_model', 'campaign');
                $data_save = array(
                    'sponsor_id' => $this->input->post('sponsor_id'),
                    'title' => $this->input->post('title'),
                    'is_private' => $this->input->post('is_private'),
                    'description' => $this->input->post('description'),
                    'highlight' => $this->input->post('highlight'),
                    'highlight_interval' => $this->input->post('highlight_interval'),
                    'starting_at' => strtotime($this->input->post('starting_at')),
                    'stopped_at' => strtotime($this->input->post('stopped_at')),
                    'candidate_vdo' => $this->input->post('candidate_vdo'),
                    'candidate_image' => $this->input->post('candidate_image'),
                    'candidate_text' => $this->input->post('candidate_text'),
                    'positive_score_reward' => $this->input->post('positive_score_reward'),
                    'view_score_reward' => $this->input->post('view_score_reward'),
                    'wilson_score_reward' => $this->input->post('wilson_score_reward'),
                    //'elo_score_reward' => $this->_parse_reward($this->input->post('elo_score_reward')),
                );
                $this->campaign->edit_campaign($campaign_id, $data_save);
                redirect('admin/campaign/list');
            }
        }

        $this->render_data['js_indy'][] = 'ckeditor/ckeditor.js';
        $this->render_data['js_indy'][] = 'ckfinder/ckfinder.js';

        $this->render_data['js'][] = 'bootstrap-datetimepicker.min.js';
        $this->render_data['css'][] = 'bootstrap-datetimepicker.min.css';

        // Load Campaign //
        $this->load->model('campaign_model', 'campaign');
        $this->render_data['campaign'] = $this->campaign->get_campaign($campaign_id);

        $this->load->model('sponsor_model', 'sponsor');
        $this->render_data['sponsor_list'] = $this->sponsor->list_sponsor();


        $this->template->write_view('main_nav', 'partials/main_nav', $this->render_data);
        $this->render_data['admin_content'] = $this->load->view('admin/campaign_edit', $this->render_data, TRUE);
        $this->template->write_view('content', 'admin/admin_wrapper', $this->render_data);



        $this->template->write('title', 'แก้ไขการแข่งขัน < จัดการรายการแข่งขัน | ' . WEB_TITLE);
        $this->template->render();
    }

    function campaign_delete($campaign_id) {
        $this->load->model('campaign_model', 'campaign');
        $this->campaign->delete_campaign($campaign_id);
        redirect('admin/campaign/list');
    }

    // </editor-fold>
    // <editor-fold desc="sponsor">
    function sponsor_list() {
        $this->load->library(array('template', 'carabiner'));

        $this->load->model('sponsor_model', 'sponsor');
        $this->render_data['sponsor_list'] = $this->sponsor->list_sponsor_count_campaign();


        $this->template->write_view('main_nav', 'partials/main_nav', $this->render_data);
        $this->render_data['admin_content'] = $this->load->view('admin/sponsor_list', $this->render_data, TRUE);
        $this->template->write_view('content', 'admin/admin_wrapper', $this->render_data);


        $this->template->write('title', 'รายการสปอนเซอร์ < จัดการสปอนเซอร์ | ' . WEB_TITLE);
        $this->template->render();
    }

    function _check_logo_upload($str) {
        // Uploading Logo //
        $config['upload_path'] = './tmp/';
        $config['allowed_types'] = 'gif|jpg|png';
        $config['encrypt_name'] = TRUE;

        $this->load->library('upload', $config);

        if (!$this->upload->do_upload('logo')) {
            $this->form_validation->set_message('_check_logo_upload', $this->upload->display_errors());
            echo $this->upload->display_errors();
            return false;
        } else {
            $data = $this->upload->data();
            $this->render_data['filename'] = $data['file_name'];
            return true;
        }
    }

    function sponsor_add() {
        $this->load->library(array('template', 'carabiner', 'form_validation'));

        if ($_POST) {
            $this->form_validation->set_rules('title', 'Title', 'required|trim|max_length[80]');

            $this->form_validation->set_rules('logo', 'Logo', 'callback__check_logo_upload');
            $this->form_validation->set_rules('css_class', 'CSS', 'required|trim|max_length[80]');


            if ($this->form_validation->run() !== FALSE) {

                rename('./tmp/' . $this->render_data['filename'], './uploads/sponsor_logo/' . $this->render_data['filename']);

                $this->load->model('sponsor_model', 'sponsor');
                $data_save = array(
                    'title' => $this->input->post('title'),
                    'css_class' => $this->input->post('css_class'),
                    'logo' => $this->render_data['filename'],
                );
                $this->sponsor->add_sponsor($data_save);
                redirect('admin/sponsor/list');
            }
        }


        $this->template->write_view('main_nav', 'partials/main_nav', $this->render_data);
        $this->render_data['admin_content'] = $this->load->view('admin/sponsor_add', $this->render_data, TRUE);
        $this->template->write_view('content', 'admin/admin_wrapper', $this->render_data);



        $this->template->write('title', 'เพิ่มสปอนเซอร์ < จัดการรายการแข่งขัน | ' . WEB_TITLE);
        $this->template->render();
    }

    function sponsor_edit($sponsor_id) {
        $sponsor_id = floor($sponsor_id);
        $this->load->library(array('template', 'carabiner', 'form_validation'));

        if ($_POST) {
            $this->form_validation->set_rules('title', 'Title', 'required|trim|max_length[80]');
            if (isset($_FILES['logo']['size']) && $_FILES['logo']['size'] > 0) {
                $this->form_validation->set_rules('logo', 'Logo', 'callback__check_logo_upload');
            }
            $this->form_validation->set_rules('css_class', 'CSS', 'required|trim|max_length[80]');


            if ($this->form_validation->run() !== FALSE) {

                $this->load->model('sponsor_model', 'sponsor');
                $data_save = array(
                    'title' => $this->input->post('title'),
                    'css_class' => $this->input->post('css_class')
                );

                if (isset($this->render_data['filename'])) {
                    // Delete Old Logo //
                    unlink('./uploads/sponsor_logo/' . $this->db->select('logo')->where('id', $sponsor_id)->get('sponsors')->row()->logo);
                    rename('./tmp/' . $this->render_data['filename'], './uploads/sponsor_logo/' . $this->render_data['filename']);
                    $data_save['logo'] = $this->render_data['filename'];
                }

                $this->sponsor->edit_sponsor($sponsor_id, $data_save);
                redirect('admin/sponsor/list');
            }
        }

        $this->load->model('sponsor_model', 'sponsor');
        $this->render_data['sponsor'] = $this->sponsor->get_sponsor($sponsor_id);


        $this->template->write_view('main_nav', 'partials/main_nav', $this->render_data);
        $this->render_data['admin_content'] = $this->load->view('admin/sponsor_edit', $this->render_data, TRUE);
        $this->template->write_view('content', 'admin/admin_wrapper', $this->render_data);



        $this->template->write('title', 'แก้ไขสปอนเซอร์ < จัดการรายการแข่งขัน | ' . WEB_TITLE);
        $this->template->render();
    }

    // </editor-fold>


    function slideshow() {
        $this->load->library(array('template', 'carabiner'));

        $this->template->write_view('main_nav', 'partials/main_nav', $this->render_data);

        //Create a new slideshow file//
        if (!is_file('./uploads/slideshow')) {
            file_put_contents('./uploads/slideshow', serialize(array()));
        }


        $this->render_data['slideshow_list'] = unserialize(file_get_contents('./uploads/slideshow'));

        function aasort($array, $key) {
            $sorter = array();
            $ret = array();
            reset($array);
            foreach ($array as $ii => $va) {
                $sorter[$ii] = $va[$key];
            }
            arsort($sorter);
            foreach ($sorter as $ii => $va) {
                $ret[$ii] = $array[$ii];
            }
            return $ret;
        }

        if (isset($_POST['add_new'])) {
            $this->render_data['slideshow_list'][] = array(
                'image_url' => $this->input->post('image_url'),
                'slideshow_url' => $this->input->post('slideshow_url'),
                'new_window' => $this->input->post('new_window'),
                'weight' => 99,
            );
            $this->render_data['slideshow_list'] = aasort($this->render_data['slideshow_list'], 'weight');
            file_put_contents('./uploads/slideshow', serialize($this->render_data['slideshow_list']));
        }

        if (isset($_POST['edit'])) {
            $new_array = array();
            if (isset($_POST['image_url'])) {
                $length = count($_POST['image_url']);

                for ($i = 0; $i < $length; $i++) {
                    $new_array[] = array(
                        'image_url' => $_POST['image_url'][$i],
                        'slideshow_url' => $_POST['slideshow_url'][$i],
                        'new_window' => $_POST['new_window'][$i],
                        'weight' => $_POST['weight'][$i],
                    );
                }
                $new_array = aasort($new_array, 'weight');
            }

            file_put_contents('./uploads/slideshow', serialize($new_array));
            $this->render_data['slideshow_list'] = $new_array;
        }

        $this->render_data['admin_content'] = $this->load->view('admin/slideshow', $this->render_data, TRUE);
        $this->template->write_view('content', 'admin/admin_wrapper', $this->render_data);
        $this->template->write('title', 'จัดการไลด์โชว์หน้าแรก | ' . WEB_TITLE);
        $this->template->render();
    }

}